//
//  BZDatabase.m
//  Benz
//
//  Created by up72-2 on 15/9/19.
//  Copyright (c) 2015年 up72_01. All rights reserved.
//

#import "BZDatabase.h"
#import "DataBaseHelper.h"
#import "Mtool.h"
static BZDatabase* _sharedManager;
@implementation BZDatabase

+(BZDatabase *)shareInstance{
    if (!_sharedManager){
        _sharedManager=[[super allocWithZone:NULL]init];
    }
    return _sharedManager;
}

- (void)createDB
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:DBPath] == NO) {
        [[DataBaseHelper sharedInstance] inDatabase:^(FMDatabase *db) {
            if ([db open]) {
                //创建离线客户信息录入表
                NSString * sql = @"CREATE TABLE 'offLineMsgTable' ('id' INTEGER PRIMARY KEY AUTOINCREMENT  NOT NULL ,'off_telephone' text,'off_personData' blob,'off_time' text,'current_user' text)";
                BOOL res = [db executeUpdate:sql];
                if (!res) {
                    NSLog(@"创建失败");
                } else {
                    NSLog(@"创建成功");
                }
            }
        }];
    }
}

//增加数据
-(void)insertOffLineMsgTable:(NSMutableDictionary *)messageDic currentTele:(NSString *)tele offTime:(NSString *)time successBlock:(updateSuccessBlock)blockS failBlock:(updateFailBlock)failB
{
    /**
     *  字典里应包含身份证号 个人信息data customId
     */
    //获取Document文件夹下的数据库文件，没有则创建
    NSData *data = [MTool returnDataWithDictionary:messageDic];
    
    FMDatabase *db = [FMDatabase databaseWithPath:DBPath];
    if (![db open]) {
        NSLog(@"open db failed");
        return;
    }
    //返回数据库中第一条满足条件的结果
    FMResultSet *rs =[db executeQuery:@"select * from offLineMsgTable where off_telephone = ? and current_user = ?",tele,[MTool getUserName]];
    
    
    if ([rs next]) {
       //已经存在同名的 替换为最新数据
        BOOL res = [db executeUpdate:@"update offLineMsgTable set off_telephone = ?,off_personData = ?,off_time= ?,current_user = ? where off_telephone = ? and current_user = ?",[messageDic objectForKey:@"mobilePhone"],data,time,[MTool getUserName],tele,[MTool getUserName]];
        if (!res) {
            failB();
        } else {
            blockS();
        }
    }
    else
    {
       //插入数据
        NSString * sql = @"insert into offLineMsgTable (off_telephone, off_personData,off_time,current_user)values(?, ?, ?, ?)";
        BOOL res = [db executeUpdate:sql,[messageDic objectForKey:@"mobilePhone"],data,time,[MTool getUserName]];
        if (!res) {
            failB();
        } else {
            blockS();
        }
    }
    
    //关闭数据库
    [db close];
}

- (NSMutableArray *)getAllOffLineData
{
    NSMutableArray *arr = [NSMutableArray array];
    FMDatabase *db = [FMDatabase databaseWithPath:DBPath];
    if (![db open]) {
        NSLog(@"open db failed");
        return nil;
    }
    //返回数据库中第一条满足条件的结果
    FMResultSet *rs =[db executeQuery:@"select * from offLineMsgTable where current_user = ?", [MTool getUserName]];
    while([rs next]) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *telephone = [rs stringForColumn:@"off_telephone"];
        NSString *time = [rs stringForColumn:@"off_time"];
        NSData *data = [rs dataForColumn:@"off_personData"];
        
        [dic setObject:telephone forKey:@"telephone"];
        [dic setObject:time forKey:@"time"];
        [dic setObject:data forKey:@"data"];
        
        [arr addObject:dic];
    }
    
    return arr;
}

//删除数据
- (void)deleteFromOffMsgTableByTel:(NSString *)telephone currentUser:(NSString *)user block:(deleteSuccessBlock)block
{
    FMDatabase *db = [FMDatabase databaseWithPath:DBPath];
    if (![db open]) {
        NSLog(@"open db failed");
        return;
    }
    //返回数据库中第一条满足条件的结果
    BOOL res = [db executeUpdate:@"delete from offLineMsgTable where off_telephone = ? and current_user = ?",telephone,[MTool getUserName]];
    if (!res) {
        block(@"fail");
    }
    else
    {
        block(@"success");
    }
    //关闭数据库
    [db close];
}
@end
